package com.yanqu.road.server.manger.activity.lottery;

import com.yanqu.road.dao.impl.activity.lottery.ActivityLotteryConfigDaoImpl;
import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.lottery.ActivityLotteryInfo;
import com.yanqu.road.entity.activity.lottery.ActivityLotteryParamInfo;
import com.yanqu.road.entity.activity.lottery.UserActivityLotteryData;
import com.yanqu.road.entity.activity.lottery.UserActivityLotteryGuaranteeData;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.lottery.ActivityLotteryConfig;
import com.yanqu.road.server.gameplayer.module.activity.lottery.ActivityLotteryModule;
import com.yanqu.road.server.gameplayer.module.activity.lottery.ActivityLotteryResult;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.utils.RandomHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityLotteryMgr extends TempMgr {

    //活动id 皮肤id(默认是0) 配置
    private static Map<Integer, Map<Integer,ActivityLotteryConfig>> configMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }


    public static void reloadActivityData() {
        getLogger().info("new reload lottery Activity start");

        Map<Integer, Map<Integer,ActivityLotteryConfig>> tempConfigMap = new ConcurrentHashMap<>();
        // 获取进行中的活动信息
        List<ActivityInfo> openActivityInfoList = NormalActivityMgr.getOpenActivityInfoList(eActivityType.ActivityLottery.getValue());
        openActivityInfoList.addAll(NormalActivityMgr.getOpenActivityInfoList(eActivityType.PeerlessBeautyLotteryActivity.getValue()));
        if (openActivityInfoList.isEmpty()) {
            getLogger().info("no lottery Activity in show time");
            configMap = new ConcurrentHashMap<>();
        }else {
            for (ActivityInfo activityInfo : openActivityInfoList) {
                ActivityLotteryConfig tmpConfig = new ActivityLotteryConfig(activityInfo);
                int tmpActivityId = activityInfo.getActivityId();
                Map<Integer,List<ActivityLotteryInfo>> configMap = new ActivityLotteryConfigDaoImpl().getActivityLotteryInfoList(tmpActivityId);
                List<ActivityLotteryInfo> allList = new ArrayList<>();
                for(List<ActivityLotteryInfo> addLsit : configMap.values()){
                    allList.addAll(addLsit);
                }
                tmpConfig.setLotteryInfoList(allList);
                Map<Integer, ActivityLotteryParamInfo> paramInfoMap = new ActivityLotteryConfigDaoImpl().getActivityLotteryParamInfoMap(tmpActivityId);
                tmpConfig.setLotteryParamInfoMap(paramInfoMap);
                // config配置
                Map<String, ActivityConfig> activityConfigMap = NormalActivityMgr.getActivityConfigMap(tmpActivityId);
                if (activityConfigMap.containsKey(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName())) {
                    tmpConfig.setEXCHANGE_SCORE_ITEM_ID(activityConfigMap.get(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName()).getIntValue());
                }
                if (activityConfigMap.containsKey("SKIN_EXTRACT_TEN_COST")) {
                    tmpConfig.setTenCost(activityConfigMap.get("SKIN_EXTRACT_TEN_COST").getValue());
                }
                tmpConfig.setCost(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_COST.getName()).getValue());
                tmpConfig.setLuckyParam(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_LUCKY_PARAM.getName()).getValue(), ";"));
                tmpConfig.setAddParam(StringUtils.stringToIntegerList(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_ADD_PARAM.getName()).getValue(), ";"));
                tmpConfig.setControlList(StringUtils.stringToStringList(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_REWARD_REPEAT_CONTROL.getName()).getValue(), "\\|"));
                tmpConfig.setActivityType(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_ACTIVITY_ID.getName()).getIntValue());
                if (activityConfigMap.containsKey(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName())) {
                    tmpConfig.setEXCHANGE_SCORE_ITEM_ID(activityConfigMap.get(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName()).getIntValue());
                }
                if (activityConfigMap.containsKey("SKIN_EXTRACT_TEN_COST")) {
                    tmpConfig.setTenCost(activityConfigMap.get("SKIN_EXTRACT_TEN_COST").getValue());
                }
                if (activityConfigMap.containsKey("SKIN_EXTRACT_SPECIAL_PARAM")) {
                    tmpConfig.setSureBigNum(activityConfigMap.get("SKIN_EXTRACT_SPECIAL_PARAM").getIntValue());
                }

                if (activityConfigMap.containsKey("SKIN_CHANGE")) {
                    tmpConfig.setSkinChange(activityConfigMap.get("SKIN_CHANGE").getIntValue());
                }

                Map<Integer, ActivityLotteryConfig> skinConfigMap = new ConcurrentHashMap<>();
                skinConfigMap.put(0, tmpConfig);
                for (int skinId : paramInfoMap.keySet()) {
                    ActivityLotteryParamInfo paramInfo = paramInfoMap.get(skinId);
                    ActivityLotteryConfig tmpSkinConfig = new ActivityLotteryConfig(activityInfo);
                    tmpSkinConfig.setLotteryInfoList(configMap.get(skinId));
                    tmpSkinConfig.setLotteryParamInfoMap(paramInfoMap);
                    if (activityConfigMap.containsKey(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName())) {
                        tmpSkinConfig.setEXCHANGE_SCORE_ITEM_ID(activityConfigMap.get(eActivityConfigType.EXCHANGE_SCORE_ITEM_ID.getName()).getIntValue());
                    }
                    if (activityConfigMap.containsKey("SKIN_EXTRACT_TEN_COST")) {
                        tmpSkinConfig.setTenCost(activityConfigMap.get("SKIN_EXTRACT_TEN_COST").getValue());
                    }
                    tmpSkinConfig.setSureBigNum(Integer.valueOf(paramInfo.getSkinExtractSpecialParam()));

                    tmpSkinConfig.setCost(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_COST.getName()).getValue());
                    tmpSkinConfig.setLuckyParam(paramInfo.getLuckyParam());
                    tmpSkinConfig.setAddParam(paramInfo.getAddParam());
                    tmpSkinConfig.setControlList(paramInfo.getControlList());
                    tmpSkinConfig.setActivityType(activityConfigMap.get(eActivityConfigType.SKIN_EXTRACT_ACTIVITY_ID.getName()).getIntValue());
                    skinConfigMap.put(skinId, tmpSkinConfig);
                }
                tempConfigMap.put(tmpActivityId, skinConfigMap);
            }

            getLogger().info("reload lottery Activity finish");
        }

        configMap = tempConfigMap;

        // 在线玩家下发数据
        for (GamePlayer gamePlayer : GamePlayerMgr.getAllOnlinePlayer()) {
            ActivityLotteryModule module = gamePlayer.getModule(ActivityLotteryModule.class);
            module.syncConfig();
            module.initUserData();
            module.syncUserData();
        }

    }

    public static ActivityLotteryResult draw(UserActivityLotteryData userData, ActivityLotteryConfig config, Random random, UserActivityLotteryGuaranteeData typeData) {
        boolean excludeHide = false;
        //前n次需共享大奖
        int n = config.getShareNTimes();
        if(n > 0){
            synchronized (userData){
                if(userData.getTotalDrawTimes() < n){
                    excludeHide = true;
                }
                //前n次没有中大奖的需要共享大奖
                if(userData.getTotalDrawTimes() < n && !userData.isGetSharedBox()){
                    if(random.nextInt(1000) < config.getShareWeigh()){
                        //中了共享大奖
                        return new ActivityLotteryResult(0, null);
                    }
                }
            }
        }
        synchronized (userData){

            ActivityLotteryInfo lotteryInfo = normalDraw(userData, config, random, excludeHide,typeData);

            return new ActivityLotteryResult(0, lotteryInfo, excludeHide);
        }
    }

    //判断是否有这个活动
    public static boolean hasActivity(){
        try{
            for(Map<Integer,ActivityLotteryConfig> skinConfigMap : configMap.values()){
                if(skinConfigMap.containsKey(0)){
                    ActivityLotteryConfig config = skinConfigMap.get(0);
                    if(config != null && config.getActivityInfo() != null && ActivityMgr.activityInShowTime(config.getActivityInfo())){
                        return true;
                    }
                }
            }
        }catch (Exception e){
            getLogger().error("lotteryMgr error." + e.getMessage(), e);
        }
        return false;
    }

    /**
     * 正常抽
     */
    public static ActivityLotteryInfo normalDraw(UserActivityLotteryData userData, ActivityLotteryConfig config, Random random, boolean excludeHide,UserActivityLotteryGuaranteeData typeData) {
        // 获取权重
        List<ActivityLotteryInfo> configList = config.getLotteryInfoList();

        // 大奖权重累加递增
        int additionWeight = 0;

        // 累加起始次数
        int addWeightMinTimes = config.getAddParam().get(0);

        boolean isGetHide = false;
        if(userData.getCommonDrawTimes() >= addWeightMinTimes){
            additionWeight += config.getAddParam().get(1) * (userData.getCommonDrawTimes() - addWeightMinTimes);
            //getLogger().debug("----------user {} 隐藏款加成 {}", userData.getUserId(), additionWeight);
//            if (config.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue() && addWeightMinTimes > 0) {
//                isGetHide = true;
//            }
        }

        //必定大奖次数
        if (config.getSureBigNum() > 0 && userData.getCommonDrawTimes() >= config.getSureBigNum()) {
            isGetHide = true;
        }

        // 已上次抽中的奖品
        Set<Integer> itemSet = new HashSet<>(userData.getGetItemMap().keySet());

        // 最后一次的奖品
        int lastItem = userData.getLastDrawItem();

        // 是否触发新奖励
        int totalCount = itemSet.size();

        // 保底，应该获得几个
        int count = getDistinctCount(config, userData,typeData);
        List<Integer> weightList = new ArrayList<>();

        // 待抽取集合
        List<ActivityLotteryInfo> itemList = new ArrayList<>();

        for (ActivityLotteryInfo itemConfig : configList) {
            // 保底，需扣除已获得
            if(count > totalCount){
                if(itemSet.contains(itemConfig.getId())){
                    continue;
                }
            }
            //是否与上次重复奖励
            if(lastItem == itemConfig.getId()){
                continue;
            }
            // 隐藏大奖
            if (excludeHide && itemConfig.getIsHide() == 1 && count <= totalCount) {
                continue;
            }

            //无双美女必中隐藏款
            if (isGetHide && itemConfig.getIsHide() == 1){
                return itemConfig;
            }
            if (itemConfig.getIsHide() == 1) {
                // 隐藏款加成
                weightList.add(itemConfig.getWeights() + additionWeight);
            } else {
                weightList.add(itemConfig.getWeights());
            }
            itemList.add(itemConfig);
        }

        // 抽
        int index = RandomHelper.getRandomIndexByWeight(weightList, random);
        return itemList.get(index);
    }

    /**
     * 获取保底需要满足几个不同的奖励
     */
    private static int getDistinctCount(ActivityLotteryConfig config, UserActivityLotteryData userData, UserActivityLotteryGuaranteeData typeData){
        int count = 0;
        if (typeData == null) {
            for (int i = 0; i < config.getControlList().size(); i++) {
                List<Integer> control = StringUtils.stringToIntegerList(config.getControlList().get(i), ";");
                if(userData.getTotalDrawTimes() >= control.get(1)){
                    count = control.get(0);
                }
            }
        }else {
            for (int i = 0; i < config.getControlList().size(); i++) {
                List<Integer> control = StringUtils.stringToIntegerList(config.getControlList().get(i), ";");
                if(typeData.getDrawCount() >= control.get(1)){
                    count = control.get(0);
                }
            }
        }


        return count;
    }


    /**
     * 获取隐藏款
     */
    public static ActivityLotteryInfo getHideItem(ActivityLotteryConfig config, Random random) {
        List<ActivityLotteryInfo> configList = config.getLotteryInfoList();
        List<Integer> weightList = new ArrayList<>();
        // 待抽取集合
        List<ActivityLotteryInfo> itemList = new ArrayList<>();
        for (ActivityLotteryInfo itemConfig : configList) {
            if(itemConfig.getIsHide() == 0){
                continue;
            }
            weightList.add(itemConfig.getWeights());
            itemList.add(itemConfig);
        }
        // 抽
        int index = RandomHelper.getRandomIndexByWeight(weightList, random);
        return itemList.get(index);
    }

    public static Map<Integer, Map<Integer,ActivityLotteryConfig>> getConfigMap() {
        return configMap;
    }

    public static ActivityLotteryConfig getActivityLotteryConfig(int activityId){
        Map<Integer,ActivityLotteryConfig> dataMap = configMap.get(activityId);
        if(null == dataMap){
            return null;
        }
        return dataMap.get(0);
    }
    public static ActivityLotteryConfig getActivityLotteryConfig(int activityId,int skinId){
        Map<Integer,ActivityLotteryConfig> dataMap = configMap.get(activityId);
        if(null == dataMap){
            return null;
        }
        return dataMap.get(skinId);
    }

    public static ActivityLotteryConfig getPeerlessBeautyLotteryConfig() {
        List<Integer> needRemove = new ArrayList<>();
        for (Map<Integer,ActivityLotteryConfig> activityLotteryConfigMap : configMap.values()) {
            ActivityLotteryConfig activityLotteryConfig = activityLotteryConfigMap.get(0);

            if (!ActivityMgr.activityInShowTime(activityLotteryConfig.getActivityInfo())) {
                needRemove.add(activityLotteryConfig.getActivityInfo().getActivityId());
                continue;
            }

            if (activityLotteryConfig.getActivityInfo().getType() == eActivityType.PeerlessBeautyLotteryActivity.getValue()) {
                return activityLotteryConfig;
            }
        }

        for (Integer activityId : needRemove) {
            configMap.remove(activityId);
        }

        return null;
    }
}
